package com.sk.skplanet.commute.controllers;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class SeoulBusApiController {
	private String baseURI;
	private String methodURIRoute;
	private String methodURIRouteAll;
	private String methodURIRouteByStation;
	private String methodURIStation;
	private String methodURIArrive;
	private String serviceKey;

	public SeoulBusApiController(String serviceKey) {
		this.baseURI = "http://ws.bus.go.kr/api/rest";
		this.methodURIArrive = "/stationinfo/getStationByUid";
		this.methodURIRouteAll = "/arrive/getArrInfoByRouteAll";
		this.methodURIRoute = "/arrive/getArrInfoByRoute";
		this.methodURIRouteByStation = "/stationinfo/getRouteByStation";
		this.methodURIStation = "/stationinfo/getStationByName";

		this.serviceKey = "KQ/vBihsFDs5MKJIN2EC14TZHo3igVdRbT9juqLj9nhX8j0rB8/JduZHIIdhM1lVDGnEZJnTtnO4ZjpbokCj/w==";
	}

	public String getStationByName(String stSrch) throws ClientProtocolException, IOException {
		String restStr = makeBaseString(methodURIStation) + "&stSrch=" + stSrch;
		return getRESTXml(restStr);
	}

	public String getStationByUid(String arsId) throws ClientProtocolException, IOException {
		String restStr = makeBaseString(methodURIArrive) + "&arsId=" + arsId;
		return getRESTXml(restStr);
	}

	public String getArrInfoByRouteAll(String busRouteId) throws ClientProtocolException, IOException {
		String restStr = makeBaseString(methodURIRouteAll) + "&busRouteId=" + busRouteId;
		return getRESTXml(restStr);
	}

	public String getArrInfoByRoute(String stId, String busRouteId, String ord) throws ClientProtocolException,
			IOException {
		String restStr = makeBaseString(methodURIRoute) + "&busRouteId=" + busRouteId + "&stId=" + stId + "&ord=" + ord;
		return getRESTXml(restStr);
	}

	public String getRouteByStation(String arsId) throws ClientProtocolException, IOException {
		String restStr = makeBaseString(methodURIRouteByStation) + "&arsId=" + arsId;
		return getRESTXml(restStr);
	}

	private String makeBaseString(String methodName) {
		String restStr = baseURI + methodName + "?ServiceKey=" + serviceKey;
		return restStr;
	}

	private String getRESTXml(String restStr) throws ClientProtocolException, IOException {
		String result = "";
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(restStr);

		HttpResponse response = client.execute(get);
		HttpEntity resEntity = response.getEntity();
		if (resEntity != null) {
			result = EntityUtils.toString(resEntity);
		}

		return result;
	}
}
